// src.module.url_mapping.module.js

var MongoDB = require('./DB/mongodb');
var mongoUtil = require('../helper/MongoUtil');
var dateUtil = require('../helper/DateformatHelper.js');
var log = require('log4js').getLogger("UrlMapping");

exports.save = function (req, res, callback) {
    var fields = {};
    if(req.body.source_url){
        fields.source_url = req.body.source_url;
    }
    if(req.body.redirect_url){
        fields.redirect_url = req.body.redirect_url;
    }
    if(req.body.state){
        fields.state = req.body.state;
    }

    if(req.query._id){
        fields.cuser = req.session.user.username;
        fields.ctime = dateUtil.getCurrentTime();
        MongoDB.update('url_mapping', {_id:req.query._id}, fields,function(err, result){
            if(err) log.error(err);
            callback(err, result);
        })
    }else{
        fields.state = 0;
        fields.create_by = req.session.user.username;
        fields.create_time = dateUtil.getCurrentTime();
        MongoDB.save('url_mapping', fields,function(err, result){
            if(err) log.error(err);
            callback(err, result);
        })
    }
};

exports.delete = function (req, res, callback) {
    MongoDB.remove('url_mapping', {_id:req.query._id},function(err, result){
        if(err) log.error(err);
        callback(err, result);
    });
};

exports.queryById = function (req, res, callback) {
    MongoDB.findById('url_mapping', req.query._id, function (err, result) {
        if(err) log.error(err);
        callback(err, result);
    });
};

exports.queryByPage = function (req, res, callback) {
    req.page = {'currentPage':req.query.currentPage||1,'pageSize':req.query.pageSize||10};
    req.page.pageSize = parseInt(req.page.pageSize);
    var conditions = {}, options ={}, p = req.query;
    options.limit = req.page.pageSize;

    if(p._id){
        conditions._id = p._id;
    }
    if (p.source_url){
        conditions.source_url = mongoUtil.like(p.source_url);
    }
    if (p.redirect_url){
        conditions.redirect_url = mongoUtil.like(p.redirect_url);
    }
    if (p.state){
        conditions.state = p.state;
    }else{
        conditions.state = 0;
    }
    MongoDB.where('url_mapping',conditions,options,function(err, result){
        if(err) log.error(err);
        callback(err, result);
    });
};
